<template>
  <el-upload
    class="upload-file"
    :action="action"
    :on-preview="handleFilePreview"
    :on-remove="handleFileRemove"
    :before-remove="handleFilebeforeRemove"
    :limit="limit"
    :auto-upload="true"
    :on-exceed="handleFileExceed"
    :file-list="fileList"
    :before-upload="handleFileBeforeUpload"
    :on-success="handleFileUploadSuccess"
    :on-error="handleFileUploadError"
    :accept="acceptType"
    :multiple="multiple"
  >
    <el-button size="small" type="primary">点击上传</el-button>
    <div slot="tip" class="el-upload__tip">上传文件不超过{{ size }}M</div>
  </el-upload>
</template>

<script>
export default {
  name: 'JspFileUpload',
  components: {},
  props: {
    // 默认列表
    defaultList: {
      type: Array,
      default: () => {
        return []
      }
    },
    // 上传地址
    action: {
      type: String,
      default: ''
    },
    // 上传类型：不填写默认所有
    // 格式：.doc,.xls,.zip,.rar等
    accept: {
      type: String,
      default: ''
    },
    // 上传数量限制
    limit: {
      type: Number,
      default: 1
    },
    // 上传数量限制，默认2M
    size: {
      type: Number,
      default: 2
    },
    // 批量上传支持
    multiple: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      fileList: this.defaultList,
      acceptType: this.accept
    }
  },
  methods: {
    // 移除文件
    handleFileRemove(file) {
      if (file && file.status === 'success') {
        this.fileList = this.fileList.filter((currentValue) => {
          return currentValue.uid !== file.uid
        })
        this.change()
        this.$emit('remove', file, this.fileList)
      }
    },
    // 文件预览/下载文件
    handleFilePreview(file) {
      this.$emit('preview', file)
    },
    // 上传数量限制
    handleFileExceed(files, fileList) {
      this.$message.warning(`最多支持上传 ${this.limit} 个文件！`)
    },
    // 文件移除前判断
    handleFilebeforeRemove(file, fileList) {
      //   return this.$confirm(`确定移除 ${file.name}？`)
    },
    // 上传前事件
    handleFileBeforeUpload(file) {
      let isFileType = true
      const ext = file.name.substring(file.name.lastIndexOf('.')).toLowerCase()
      if (this.accept !== '') {
        isFileType = this.acceptType.split(',').some((e) => {
          return e.replace(/\s+/g, '').toLowerCase() === ext
        })
        if (!isFileType) {
          this.$message.error(
            '文件类型不正确，支持类型' + this.acceptType + '，请重新选择!'
          )
        }
      }
      const isSize = file.size / 1024 / 1024 < this.size
      if (!isSize) {
        this.$message.error('文件大小不能超过 ' + this.size + 'MB!')
      }
      return isFileType && isSize
    },
    // 上传成功
    handleFileUploadSuccess(response, file, fileList) {
      // response数据结构由后端生成
      if (response.status === 'success') {
        // 以下内容在实际项目开发中还需按需进行修改
        const { id, name, path, url } = response
        this.fileList.push({ id: id, name: name, path: path, url: url })
        this.change()
      }
      this.$emit('success', response, file, fileList)
    },
    // 上传失败：上传请求地址、参数错误或服务器请求错误等情况
    handleFileUploadError(err, file, fileList) {
      this.$emit('error', err, file, fileList)
    },
    // 改变：上传成功、删除图片时激活
    // 返回：当前文件数组、图片id集
    change() {
      const ids = this.fileList.map((currentValue) => currentValue.id).join(',')
      const result = {
        ids,
        fileList: this.fileList
      }
      this.$emit('change', result)
    }
  }
}
</script>

<style>
</style>
